﻿namespace mVids
{
    using MediaPortal.GUI.Library;
    using System;
    using System.Collections.Generic;
    using System.Drawing;

    internal class mosaicGenerator
    {
        public Image getMosaic(List<string> images, Rectangle targetRect, string thumbdir, int mosaicWidth, int mosaicHeight)
        {
            Image image = new Bitmap(targetRect.Width, targetRect.Height);
            Graphics graphics = Graphics.FromImage(image);
            Point location = new Point(0, 0);
            List<int> list = new List<int>();
            for (int i = 0; i < images.Count; i++)
            {
                int index = new Random().Next(0, images.Count - 1);
                index = i;
                Image image2 = Image.FromFile(images[index]);
                int width = image2.Width;
                int height = image2.Height;
                if (height > mosaicHeight)
                {
                    height = mosaicHeight;
                    width = (image2.Width * height) / image2.Height;
                }
                else if (width > mosaicWidth)
                {
                    width = mosaicWidth;
                    height = (image2.Height * width) / image2.Width;
                }
                if ((location.Y + height) > targetRect.Height)
                {
                    Log.Debug("Music Video DB - Mosaic size limit reached, returning", new object[0]);
                    return image;
                }
                if ((location.X + width) > image.Width)
                {
                    location = new Point(0, location.Y + mosaicHeight);
                }
                graphics.DrawImage(image2.GetThumbnailImage(width, height, null, IntPtr.Zero), new Rectangle(location, new Size(width, height)));
                location.X += width;
                if ((location.X + mosaicWidth) > image.Width)
                {
                    location = new Point(0, location.Y + mosaicHeight);
                }
                if ((location.Y + 5) > targetRect.Height)
                {
                    Log.Debug("Music Video DB - Mosaic size limit reached, returning", new object[0]);
                    return image;
                }
                images.RemoveAt(index);
            }
            return image;
        }
    }
}

